package com.moodbox.server.mood.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moodbox.server.common.exception.BusinessException;
import com.moodbox.server.mood.dto.MoodRecordDTO;
import com.moodbox.server.mood.entity.MoodRecord;
import com.moodbox.server.mood.mapper.MoodRecordMapper;
import com.moodbox.server.mood.service.MoodRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 心情记录服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MoodRecordServiceImpl extends ServiceImpl<MoodRecordMapper, MoodRecord> implements MoodRecordService {

    private final MoodRecordMapper moodRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MoodRecord createMoodRecord(String userId, MoodRecordDTO moodRecordDTO) {
        // 检查参数
        if (moodRecordDTO == null || moodRecordDTO.getMoodLevel() == null) {
            throw new BusinessException("心情记录数据不完整");
        }

        // 设置记录日期，如果未提供则使用当前时间
        if (moodRecordDTO.getRecordDate() == null) {
            moodRecordDTO.setRecordDate(LocalDateTime.now());
        }

        // 创建实体对象
        MoodRecord moodRecord = new MoodRecord();
        BeanUtils.copyProperties(moodRecordDTO, moodRecord);
        
        // 设置用户ID和心情等级
        moodRecord.setUserId(userId);
        moodRecord.setMoodLevel(moodRecordDTO.getMoodLevel().getCode());
        
        // 处理标签和图片列表
        if (moodRecordDTO.getMoodTags() != null && !moodRecordDTO.getMoodTags().isEmpty()) {
            moodRecord.setMoodTags(String.join(",", moodRecordDTO.getMoodTags()));
        }
        
        if (moodRecordDTO.getMoodImages() != null && !moodRecordDTO.getMoodImages().isEmpty()) {
            moodRecord.setMoodImages(String.join(",", moodRecordDTO.getMoodImages()));
        }

        // 保存记录
        save(moodRecord);
        log.info("创建心情记录：{}", moodRecord.getId());
        return moodRecord;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MoodRecord updateMoodRecord(String userId, MoodRecordDTO moodRecordDTO) {
        // 检查参数
        if (moodRecordDTO == null || moodRecordDTO.getId() == null) {
            throw new BusinessException("心情记录数据不完整");
        }

        // 查询原记录
        MoodRecord existingRecord = getById(moodRecordDTO.getId());
        if (existingRecord == null) {
            throw new BusinessException("心情记录不存在");
        }

        // 检查权限
        if (!existingRecord.getUserId().equals(userId)) {
            throw new BusinessException("无权修改该心情记录");
        }

        // 更新实体对象
        if (moodRecordDTO.getMoodLevel() != null) {
            existingRecord.setMoodLevel(moodRecordDTO.getMoodLevel().getCode());
        }
        
        if (moodRecordDTO.getMoodDescription() != null) {
            existingRecord.setMoodDescription(moodRecordDTO.getMoodDescription());
        }
        
        if (moodRecordDTO.getMoodTags() != null) {
            existingRecord.setMoodTags(String.join(",", moodRecordDTO.getMoodTags()));
        }
        
        if (moodRecordDTO.getMoodImages() != null) {
            existingRecord.setMoodImages(String.join(",", moodRecordDTO.getMoodImages()));
        }
        
        if (moodRecordDTO.getLocation() != null) {
            existingRecord.setLocation(moodRecordDTO.getLocation());
        }
        
        if (moodRecordDTO.getWeather() != null) {
            existingRecord.setWeather(moodRecordDTO.getWeather());
        }
        
        if (moodRecordDTO.getActivity() != null) {
            existingRecord.setActivity(moodRecordDTO.getActivity());
        }
        
        if (moodRecordDTO.getRecordDate() != null) {
            existingRecord.setRecordDate(moodRecordDTO.getRecordDate());
        }

        // 保存更新
        updateById(existingRecord);
        log.info("更新心情记录：{}", existingRecord.getId());
        return existingRecord;
    }

    @Override
    public MoodRecord getMoodRecordByDate(String userId, LocalDateTime recordDate) {
        if (userId == null || recordDate == null) {
            return null;
        }
        
        LambdaQueryWrapper<MoodRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MoodRecord::getUserId, userId)
                   .ge(MoodRecord::getRecordDate, recordDate.toLocalDate().atStartOfDay())
                   .lt(MoodRecord::getRecordDate, recordDate.toLocalDate().plusDays(1).atStartOfDay())
                   .orderByDesc(MoodRecord::getCreateTime)
                   .last("LIMIT 1");
        
        return getOne(queryWrapper);
    }

    @Override
    public List<MoodRecord> listMoodRecords(String userId, LocalDateTime startDate, LocalDateTime endDate) {
        LambdaQueryWrapper<MoodRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MoodRecord::getUserId, userId);
        
        if (startDate != null) {
            queryWrapper.ge(MoodRecord::getRecordDate, startDate);
        }
        
        if (endDate != null) {
            queryWrapper.le(MoodRecord::getRecordDate, endDate);
        }
        
        queryWrapper.orderByDesc(MoodRecord::getRecordDate);
        
        return list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMoodRecord(String userId, String recordId) {
        // 查询记录
        MoodRecord record = getById(recordId);
        if (record == null) {
            return false;
        }
        
        // 检查权限
        if (!record.getUserId().equals(userId)) {
            throw new BusinessException("无权删除该心情记录");
        }
        
        // 删除记录
        boolean result = removeById(recordId);
        if (result) {
            log.info("删除心情记录：{}", recordId);
        }
        return result;
    }
} 